package Utils;

import common.ServerInterface;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Excel读取工具类
 * Author:xuedonglei
 * Date: 2017/7/1
 */
public class ExcelReader {

    private List<ServerInterface> serverInterfaceList;
    private Logger logger = MyLogs.getLogger();

    /**
     * 读取excel文件
     *
     * @param filepath
     */
    public List<ServerInterface> getExcelData(String filepath) {

        String ext = getFileExt(filepath);
        if ("xls".equals(ext)) {
            logger.info("读取xls文件开始");
            return readXls(filepath);
        } else if ("xlsx".equals(ext)) {
            logger.info("读取xlsx文件开始");
            //printList(readXlsx(filepath));
            return readXlsx(filepath);
        } else {
            logger.error("testcase文件类型错误！");
            return null;
        }
    }

    /**
     * 打印serverinterface对象内容到屏幕
     *
     * @param list
     */
    private void printList(List<ServerInterface> list) {
        for (ServerInterface serverInterface :
                list) {
            logger.info("desc:" + serverInterface.getDescription() + "\nhost:" + serverInterface.getHost()
                    + "\nurl:" + serverInterface.getUrl() + "\nparam:" + serverInterface.getParam()
                    + "\nheader:" + serverInterface.getHeader() + "\nbody:" + serverInterface.getBody()
                    + "\nexpect:" + serverInterface.getExpect());
        }
    }


    /**
     * 获取文件扩展名
     *
     * @param filepath
     * @return
     */
    private String getFileExt(String filepath) {
        if (filepath.contains(".")) {
            String[] str = filepath.split("\\.", 2);
            return str[1];
        } else {
            logger.error("文件名错误！");
        }

        return null;
    }


    /**
     * 读取xls格式的文件
     *
     * @param filepath
     */
    private List<ServerInterface> readXls(String filepath) {
        HSSFWorkbook workbook;
        serverInterfaceList = new ArrayList<ServerInterface>();
        try {

            InputStream is = new FileInputStream(filepath);
            workbook = new HSSFWorkbook(is);
            HSSFSheet sheet = workbook.getSheetAt(0);
            for (int i = 0; i < sheet.getLastRowNum(); i++) {
                HSSFRow row = sheet.getRow(i);
                //获取每一行的单元格内容
                HSSFCell desc = row.getCell(0);
                HSSFCell host = row.getCell(1);
                HSSFCell url = row.getCell(2);
                HSSFCell param = row.getCell(3);
                HSSFCell header = row.getCell(4);
                HSSFCell body = row.getCell(5);
                HSSFCell expect = row.getCell(6);
                //设置接口对象内容
                ServerInterface serverInterface = new ServerInterface();
                serverInterface.setDescription(getHSSFCellValue(desc));
                serverInterface.setHost(getHSSFCellValue(host));
                serverInterface.setUrl(getHSSFCellValue(url));
                serverInterface.setParam(getHSSFCellValue(param));
                serverInterface.setHeader(getHSSFCellValue(header));
                serverInterface.setBody(getHSSFCellValue(body));
                serverInterface.setExpect(getHSSFCellValue(expect));
                //将对象添加到list内
                serverInterfaceList.add(serverInterface);
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return serverInterfaceList;
    }


    /**
     * 读取xlsx格式的文件
     *
     * @param filepath
     */
    private List<ServerInterface> readXlsx(String filepath) {
        XSSFWorkbook workbook;
        serverInterfaceList = new ArrayList<>();

        try {
            File file = new File(filepath);
            FileInputStream is = new FileInputStream(file);
            workbook = new XSSFWorkbook(is);
            XSSFSheet sheet = workbook.getSheetAt(0);
            logger.info("sheet共：" + sheet.getLastRowNum() + " 行");
            for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
                XSSFRow row = sheet.getRow(i);
                logger.info("=============开始遍历第 " + i + " 行===========");

                /*
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    XSSFCell cell = row.getCell(j);
                    System.out.println("-------start print：" + j + " 个单元格-------");
                    System.out.println(getXSSFCellValue(cell));
                }*/


                //获取每一行的单元格内容
                if (row != null) {
                    XSSFCell desc = row.getCell(0);
                    XSSFCell host = row.getCell(1);
                    XSSFCell url = row.getCell(2);
                    XSSFCell param = row.getCell(3);
                    XSSFCell header = row.getCell(4);
                    XSSFCell body = row.getCell(5);
                    XSSFCell expect = row.getCell(6);
                    //设置接口对象内容
                    ServerInterface serverInterface = new ServerInterface();
                    serverInterface.setDescription(getXSSFCellValue(desc));
                    serverInterface.setHost(getXSSFCellValue(host));
                    serverInterface.setUrl(getXSSFCellValue(url));
                    serverInterface.setParam(getXSSFCellValue(param));
                    serverInterface.setHeader(getXSSFCellValue(header));
                    serverInterface.setBody(getXSSFCellValue(body));
                    serverInterface.setExpect(getXSSFCellValue(expect));
                    //将对象添加到list内
                    serverInterfaceList.add(serverInterface);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return serverInterfaceList;
    }


    private String getHSSFCellValue(HSSFCell cell) {
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC:
                // 数字
                return String.valueOf(cell.getNumericCellValue());

            case HSSFCell.CELL_TYPE_STRING:
                // 字符串
                return cell.getStringCellValue();

            case HSSFCell.CELL_TYPE_BOOLEAN:
                // Boolean
                return String.valueOf(cell.getBooleanCellValue());

//            case HSSFCell.CELL_TYPE_FORMULA:
//
//
//                System.out.print(cell.getCellFormula() + "   ");
//                break;
            case HSSFCell.CELL_TYPE_BLANK:
                // 空值
                return " ";

            case HSSFCell.CELL_TYPE_ERROR:
                // 故障
                return " ";

            default:
                return "未知类型";

        }

    }

    private String getXSSFCellValue(XSSFCell cell) {

        if (cell != null) {
            switch (cell.getCellType()) {
                case XSSFCell.CELL_TYPE_NUMERIC:
                    // 数字
                    return String.valueOf(cell.getNumericCellValue());

                case XSSFCell.CELL_TYPE_STRING:
                    // 字符串
                    return cell.getStringCellValue();

                case XSSFCell.CELL_TYPE_BOOLEAN:
                    // Boolean
                    return String.valueOf(cell.getBooleanCellValue());

            /*case HSSFCell.CELL_TYPE_FORMULA:


                System.out.print(cell.getCellFormula() + "   ");
                break;
                */

                case XSSFCell.CELL_TYPE_BLANK:
                    // 空值
                    return " ";

                case XSSFCell.CELL_TYPE_ERROR:
                    // 故障
                    return " ";

                default:
                    return "未知类型";

            }
        }

        return null;
    }

    public Object[][] convertObject(List<ServerInterface> sList) {
        List<String[]> ss = new ArrayList<>();
        for (ServerInterface sif : sList) {
            String[] data = new String[7];
            data[0] = sif.getDescription();
            data[1] = sif.getHost();
            data[2] = sif.getUrl();
            data[3] = sif.getParam();
            data[4] = sif.getHeader();
            data[5]  = sif.getBody();
            data[6]  = sif.getExpect();
            //把一行记录以字符串数组方式加入List
            ss.add(data);
        }

        /*
        for (String[] strList : ss) {
            for (String x : strList) {
                System.out.println(x);
            }
        }*/

        Object[][] objects = new Object[ss.size()][7];
        for (int i = 0; i < ss.size(); i++) {
            String[] strList = ss.get(i);
            for (int j = 0; j < strList.length; j++) {
                objects[i][j] = strList[j];
            }
        }

        return objects;
    }

    public static void main(String[] args) {
        ExcelReader reader = new ExcelReader();
        List<ServerInterface> list = reader.getExcelData("xlscase/testcase.xlsx");
        reader.printList(list);

    }
}
